import os
import math
import matplotlib
matplotlib.use('Agg')  # 使用非交互式后端
import matplotlib.pyplot as plt
import subprocess
from PyQt5.QtWidgets import QMessageBox

class QuadrantVisualizer:
    def __init__(self):
        pass

    def run_separation(self):
        """运行象限分离处理"""
        try:
            # 读取组合数据文件
            current_dir = os.path.dirname(os.path.abspath(__file__))
            input_file = os.path.join(current_dir, "data", "combined_output.txt")
            
            # 读取和处理数据
            with open(input_file, 'r', encoding='utf-8') as f:
                # 读取矩阵尺寸
                rows, cols = map(int, f.readline().strip().split())
                
                # 读取矩阵
                matrix = []
                for _ in range(rows):
                    line = f.readline().strip().split()
                    row = [1 if x == '@' else 0 for x in line]
                    matrix.append(row)
                
                # 读取线段数量
                num_segments = int(f.readline().strip())
                
                # 读取所有线段
                segments = []
                for _ in range(num_segments):
                    x1, y1, x2, y2 = map(int, f.readline().strip().split())
                    segments.append((x1, y1, x2, y2))

            # 按象限分类线段
            quadrants = [[] for _ in range(4)]
            for seg in segments:
                x1, y1, x2, y2 = seg
                dx, dy = x2 - x1, y2 - y1
                if dx == 0 and dy == 0:
                    continue
                
                angle = math.degrees(math.atan2(dy, dx))
                if angle < 0:
                    angle += 360
                    
                # 分配到对应象限
                quadrant_idx = int(angle // 90)
                quadrants[quadrant_idx].append(seg)

            # 保存每个象限的数据
            for i in range(4):
                filename = os.path.join(current_dir, "data", f"quadrant_{i+1}.txt")
                with open(filename, 'w', encoding='utf-8') as f:
                    # 写入矩阵尺寸
                    f.write(f"{rows} {cols}\n")
                    # 写入矩阵
                    for row in matrix:
                        f.write(' '.join(['@' if cell else '.' for cell in row]) + '\n')
                    # 写入当前象限的线段
                    f.write(f"{len(quadrants[i])}\n")
                    for seg in quadrants[i]:
                        f.write(' '.join(map(str, seg)) + '\n')

            # 生成可视化
            self.generate_visualization(quadrants)
            
            return quadrants
            
        except Exception as e:
            raise Exception(f"象限处理失败: {str(e)}")

    def generate_visualization(self, quadrants):
        """生成象限可视化图表"""
        plt.figure(figsize=(12, 12))
        colors = ['#FF6B6B', '#4ECDC4', '#556270', '#C44D58']
        quadrant_names = ['I', 'II', 'III', 'IV']

        # 计算所有点的范围
        all_x = []
        all_y = []
        for quadrant in quadrants:
            for seg in quadrant:
                x1, y1, x2, y2 = seg
                all_x.extend([x1, x2])
                all_y.extend([y1, y2])

        if not all_x or not all_y:
            raise Exception("没有找到有效的路径点")

        x_range = max(all_x) - min(all_x)
        y_range = max(all_y) - min(all_y)
        max_range = max(x_range, y_range) or 10
        padding = max_range * 0.15

        # 绘制四个象限
        for i, segments in enumerate(quadrants):
            plt.subplot(2, 2, i + 1)
            plt.title(f'Quadrant {quadrant_names[i]} (n={len(segments)})')
            plt.gca().set_facecolor('#F7F7F7')
            
            plt.xlim(min(all_x) - padding, max(all_x) + padding)
            plt.ylim(min(all_y) - padding, max(all_y) + padding)
            plt.grid(True, linestyle='--', alpha=0.3)
            plt.axhline(y=0, color='black', linewidth=0.5)
            plt.axvline(x=0, color='black', linewidth=0.5)

            for seg in segments:
                x1, y1, x2, y2 = seg
                plt.arrow(x1, y1, x2-x1, y2-y1,
                         color=colors[i],
                         head_width=max_range*0.02,
                         head_length=max_range*0.03,
                         length_includes_head=True,
                         linewidth=1.5,
                         alpha=0.8)

            plt.axis('equal')

        plt.tight_layout(pad=3.0)
        save_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 
                                "data", "quadrant_visualization.png")
        plt.savefig(save_path, dpi=150, bbox_inches='tight', facecolor='white')
        plt.close()

    def show_visualization(self):
        """展示可视化图片"""
        try:
            current_dir = os.path.dirname(os.path.abspath(__file__))
            image_path = os.path.join(current_dir, "data", "quadrant_visualization.png")
            if os.path.exists(image_path):
                if os.name == 'nt':  # Windows
                    os.startfile(image_path)
                elif os.name == 'posix':  # Linux/Mac
                    subprocess.call(['xdg-open', image_path])
            else:
                raise Exception("可视化图片不存在，请先生成可视化图表")
        except Exception as e:
            raise Exception(f"展示可视化图片时出错: {str(e)}")

if __name__ == '__main__':
    visualizer = QuadrantVisualizer()
    visualizer.run_separation()